const http = require("http");
const data = require("./data/index.json");
const server = http.createServer((req, res) => {
  res.setHeader("content-type", "text/html;charset=utf-8");
  // 把地址存起来
  let url = new URL(req.url, "http://127.0.0.1");
  console.log(url.pathname);
  // 新闻列表页
  if (url.pathname === "/") {
    let str = `<ul>`;
    data.forEach((item) => {
      str += `<li><a href='detail?id=${item.id}'>${item.newsTitle}</a></li>`;
    });
    str += `</ul>`;
    res.end(str);
  }

  // 新闻详情页面

  // 这个是字符串转数组，截取数组的第一项
  if (url.pathname === "/detail") {
    let Id = req.url.split("=")[1];

    // 根据id查找内容
    let content = data.find((v) => {
      // 返回数组中满足的条件的返回
      return v.id == Id;
    });

    let deTail = `<h1>${content.newsTitle}</h1>
  <div>${content.newsContent}</div>
  `;
    res.end(deTail);
  }
});

server.listen(80, () => {
  console.log("开始启动");
});
